import Vuex from "vuex";
import Vue from 'vue';
import axios from "axios";
import md5 from 'md5'

import user from './user';
import items from "./items";
import manage from "./manage";
import cart from "./cart";
import order from "./order";
import salesOrder from "./salesOrder";


Vue.use(Vuex);


const store= new Vuex.Store({
  modules:{
    user,items,manage,cart,order,salesOrder
  },
  state:{
    onLogin:false,
    registerSelectID:false,
    register:{
      identity:'',
      username:'',
      password:'',
      email:''
    },
    login:{
      identity:'',
      username:'',
      password:''
    }
  },
  mutations:{
    registerSelectIdentity(state,identity){
      state.registerSelectID=true;
      state.register.identity=identity;
      console.log('注册身份事件触发');
    },
    usernameSet(state,username){
      state.register.username=username;
    },
    passwordSet(state,password){
      //密码发送前需要加密
      state.register.password=md5(password);
    },
    emailSet(state,email){
      state.register.email=email;
    },
    clearRegister(state){
      state.register.password='';
    }
  },
  actions:{
    login({commit,state},{identity,username,password}){
      [state.login.identity,state.login.username,state.login.password]=[identity,username,md5(password)];
      return new Promise(((resolve, reject) => {
        axios.post('',JSON.stringify(state.login)).then((response)=>{
          if (response.status===200){
            state.login.password='';
            resolve();
          }
        }).catch((e)=>{
          reject(e);
        })
      }))
    },
    register({commit,state},{username,password,emailAddress}){
      //存储变量
      commit('usernameSet',username);
      commit('passwordSet',password);
      commit('emailSet',emailAddress);

      console.log(state);

      //post提交注册申请
      return new Promise((resolve,reject)=>{
        axios.post('',JSON.stringify(state.register)).then((response)=>{
          if (response.status===200){
            commit('clearRegister');
            resolve();
          }
        }).catch((e)=>{
            reject(e);
        })
      })
    },


    pay(){

    }
  },

})

export default store;

// module.exports=store;
